import React, { useCallback, useState } from 'react';
import { Col, Form, Input, Row, Select, TreeSelect } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import { UploadFormCommon } from '@/components/UploadForm';
import AdminAriea from '@/components/AdminAriea';
import { useRequest } from 'umi';
import { adminAreadDataGet, loadMdicMap } from '@/services/BaseLayout';
import { getLoadMapList, getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { RegularExpression } from '@/common/constVariable';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import moment from 'moment';

interface IUpdateNeedMaterialModalRightFormAPI {
  formRef: any;
  prefixCls: string;
}

export const UpdateNeedMaterialModalRightForm: React.FC<IUpdateNeedMaterialModalRightFormAPI> = ({ formRef, prefixCls }) => {
  /**保存上级岗位搜索输入框的值*/
  const [treeSearch, setTreeSearch] = useState<string>('');

  /**货物类-字典编码*/
  const HWL_Code = `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1000`;

  // /**获取数据字典*/
  // const loadMdicMapList = useRequest(() => {
  //   return loadMdicMap([
  //     `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`,
  //     `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`,
  //     `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`,
  //     `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`,
  //     `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`,
  //   ]);
  // });

  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`,
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`,
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`,
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`,
  ];

  const { loadMapInfo: loadMdicMapList, mapLoading } = getLoadMapList(loadMdicIds);

  /**获取行政区域*/
  const areadList = useRequest(() => {
    return adminAreadDataGet({});
  });

  /**保存TextArea是否输入*/
  const [isShowChange, setIsShowChange] = useState(false);

  // 处理树数据
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      const name = item?.name;
      const nameLength = name?.length;
      const select = name?.search(treeSearch);
      const searchLength = treeSearch?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = treeSearch;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );

      if (item?.children && item?.children?.length > 0) {
        return {
          ...item,
          title: (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                paddingRight: 20,
              }}
              id={item?.id}
            >
              {titleTree}
            </div>
          ),
          searchTitle: item?.name,
          key: item?.id,
          value: item?.id,
          children: orgTreeData(item?.children),
        };
      }
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              paddingRight: 20,
            }}
            id={item?.id}
          >
            {titleTree}
          </div>
        ),
        searchTitle: item?.name,
        key: item?.id,
        value: item?.id,
      };
    });
  };

  // 获取搜索框输入的值
  const treeSearchValue = useCallback(
    (valText: string) => {
      setTreeSearch(valText);
    },
    [treeSearch],
  );

  const onSelect = (value: any, node: any) => {
    formRef?.setFieldsValue({
      materialNum: node?.shortCode + moment().format('YYYY').slice(2),
    });
  };
  return (
    <>
      <ScrollBarLayout style={{ padding: '0.5rem 0' }}>
        <div className={Cls(pageStyles['fromView-styles'], prefixCls + 'addMaterialForm')}>
          <Form form={formRef}>
            <Row>
              <Col span={12}>
                <Form.Item
                  label="物料类型"
                  name="materialType"
                  rules={[
                    {
                      required: true,
                      message: '请选择物料类型',
                    },
                  ]}
                >
                  <TreeSelect
                    placeholder="请选择"
                    showSearch={true}
                    treeNodeFilterProp={'searchTitle'}
                    treeData={orgTreeData(loadMdicMapList?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`])}
                    onSearch={treeSearchValue}
                    onSelect={onSelect}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="物料编码"
                  name="materialNum"
                  rules={[
                    // {
                    //   required: true,
                    //   message: '请输入物料编码',
                    // },
                    {
                      pattern: RegularExpression.numberOrLetter,
                      message: '编码格式不正确！',
                    },
                  ]}
                >
                  <Input placeholder="自动生成" disabled />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="物料名称"
                  name="fullName"
                  rules={[
                    {
                      required: true,
                      message: '请输入物料名称',
                    },
                  ]}
                >
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="供货分类"
                  name="supplyType"
                  // rules={[
                  //   {
                  //     required: true,
                  //     message: '请选择供货分类',
                  //   },
                  // ]}
                  initialValue={HWL_Code}
                >
                  <Select placeholder="请选择" loading={mapLoading} disabled>
                    {loadMdicMapList?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`]?.map((item: any) => {
                      if (item?.id === HWL_Code) {
                        return (
                          <Select.Option key={item?.id} value={item?.id}>
                            {item?.name}
                          </Select.Option>
                        );
                      }
                    })}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <Form.Item
                  label="规格要求(参数)"
                  name="specInfo"
                  rules={[
                    {
                      required: true,
                      message: '请输入规格要求(参数)',
                    },
                    // {
                    //   pattern: RegularExpression?.noChinese,
                    //   message: '规格参数只能填字母和数字！',
                    // },
                  ]}
                >
                  {/* <Input placeholder="请输入" /> */}
                  <Input.TextArea placeholder="请输入" allowClear maxLength={500} autoSize={{ minRows: 3 }} showCount />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <Form.Item
                  label="规格型号"
                  name="modelNum"
                  rules={[
                    {
                      required: false,
                      message: '请输入规格型号',
                    },
                  ]}
                >
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item
                  label="参考单价"
                  name="unitPrice"
                  rules={[
                    {
                      required: false,
                      message: '请输入参考单价',
                    },
                    {
                      pattern: RegularExpression?.floatNumber,
                      message: '参考单价只能填数字！',
                    },
                    {
                      pattern: /^\d+(\.\d{1,2})?$/,
                      message: '做多可保留两位小数！',
                    },
                  ]}
                >
                  <Input placeholder="请输入" addonAfter={'元'} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="量化单位"
                  name="unitBusiness"
                  rules={[
                    {
                      required: true,
                      message: '请选择量化单位',
                    },
                  ]}
                >
                  <Select placeholder="请选择" loading={mapLoading}>
                    {loadMdicMapList?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`]?.map((item: any) => {
                      return (
                        <Select.Option key={item?.id} value={item?.id}>
                          {item?.name}
                        </Select.Option>
                      );
                    })}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <Form.Item label="物料简介" name="paramsInfo">
                  <Input.TextArea placeholder="请输入" allowClear maxLength={200} autoSize={{ minRows: 3 }} showCount />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <UploadFormCommon
                  form={formRef}
                  fileFormName={'imageInfo'}
                  fileFormDelName={'delLicenceUrl'}
                  name={'attachFile'}
                  spanCol={24}
                  inRowProportion={12}
                  label="相关图片"
                  required={false}
                  accept={'.jpg|.png|.jpeg'}
                  url={`/materialController/uploadFile`}
                  downloadUrl={`/materialController/downloadFile`}
                  delFunc={() => {}}
                  maxFile={5}
                  defaultFiles={null}
                  fieldBusiPath={'purchase/need'}
                >
                  上传
                </UploadFormCommon>
              </Col>
            </Row>
            <Row>
              <Col></Col>
            </Row>
          </Form>
        </div>
      </ScrollBarLayout>
    </>
  );
};
